<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图片类型" prop="imageType">
        <el-select v-model="queryParams.imageType" placeholder="请选择图片类型" clearable>
          <el-option v-for="dict in dict.type.sys_goods_img_type" :key="dict.value" :label="dict.label"
                     :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="存储源" prop="imageServer">
        <el-select v-model="queryParams.imageServer" placeholder="请选择图片存储源" clearable>
          <el-option v-for="dict in dict.type.sys_goods_res_path" :key="dict.value" :label="dict.label"
                     :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品编码" prop="gNumber">
        <el-input v-model="queryParams.gNumber" placeholder="请输入商品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="gName">
        <el-input v-model="queryParams.gName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="图片名称" prop="imageName">
        <el-input v-model="queryParams.imageName" placeholder="请输入图片名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="图片状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
                     :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="上传时间">
        <el-date-picker
          v-model="queryParams.params.times"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['goods:images:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['goods:images:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['goods:images:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['goods:images:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border fit stripe :data="imagesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="图片id" align="center" prop="imageId" /> -->
      <el-table-column label="商品编码" align="center" prop="gNumber" width="220" :show-overflow-tooltip="true" />
      <el-table-column label="顺序" align="center" prop="orderNum" width="60" />
      <el-table-column label="商品名称" align="center" prop="gName" :show-overflow-tooltip="true" />
      <el-table-column label="图片类型" align="center" prop="imageType" width="80" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_img_type" :value="scope.row.imageType" />
        </template>
      </el-table-column>
      <el-table-column label="图片存储源" align="center" prop="imageServer" width="90" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_res_path" :value="scope.row.imageServer" />
        </template>
      </el-table-column>
      <el-table-column label="图片名称" align="center" prop="imageName" :show-overflow-tooltip="true" />
      <el-table-column label="图片" align="center" prop="imagePath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imagePath" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
      <el-table-column label="上传人" align="center" prop="createBy" width="80" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="delFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.delFlag" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['goods:images:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     style="color: #f56c6c"
                     v-hasPermi="['goods:images:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改图片资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" :close-on-click-modal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="图片类型" prop="imageType">
              <el-select v-model="form.imageType" placeholder="请选择图片类型" style="width: 100%;">
                <el-option v-for="dict in dict.type.sys_goods_img_type" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储源" prop="imageServer">
              <el-select v-model="form.imageServer" placeholder="请选择图片存储源" style="width: 100%;" :disabled="isDisabled(form)" >
                <el-option v-for="dict in dict.type.sys_goods_res_path" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="gNumber">
              <el-input v-model="form.gNumber" placeholder="请输入商品编码" @change="handleGNumberChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="gName">
              <el-input v-model="form.gName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="图片名称" prop="imageName">
              <el-input v-model="form.imageName" placeholder="请输入图片名称" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input v-model="form.orderNum" placeholder="顺序" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="delFlag">
              <el-radio-group v-model="form.delFlag">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                          :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.imageServer === 'http'">
          <el-col :span="24">
            <el-form-item label="网络图片">
              <template v-for="(httpPath, index) in form.imageHttpPath2">
                <el-input v-model="form.imageHttpPath2[index]" placeholder="请输入网络图片链接" :disabled="isDisabled(form)">  >
                  <template slot="append" v-if="!isDisabled(form)" >
                    <el-button type="primary" plain icon="el-icon-plus" @click="addHttpImage"
                               v-if="index <= 6 && index === form.imageHttpPath2.length-1" >添加</el-button>
                    <el-button type="danger"  plain icon="el-icon-delete" @click="delHttpImage(index)"
                               v-if="index !== 0 || form.imageHttpPath2.length>1" >删除</el-button>
                  </template>
                </el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <template v-if="form.imageHttpPath2 && form.imageHttpPath2.length > 0" >
                <el-image class="http-image-list" fit="contain" v-for="httpPath in form.imageHttpPath2"
                          :src="httpPath" :preview-src-list="getPreviewSrcList(httpPath)" />
              </template>
              <el-image v-else fit="contain" style="height: 100px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="24">
            <el-form-item label="上传图片">
              <image-upload ref="uploadImage" v-model="form.imagePath" :auto-upload="false"
                            :limit="uploadLimit(form)" @success="handleImageSuccess" :disabled="isDisabled(form)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listImages, getImages, delImages, addImages, updateImages } from "@/api/goods/images";
import { getMainByGNumber } from "@/api/goods/main";

export default {
  name: "Images",
  dicts: ['sys_goods_img_type', 'sys_goods_res_path', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 图片资源表格数据
      imagesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gNumber: null,
        gName: null,
        imageType: null,
        imageName: null,
        imageServer: null,
        imagePath: null,
        orderNum: null,
        params: {
          times: [],
          startTime: null,
          endTime: null,
        }
      },
      // 本地图片资源地址
      imgServe: process.env.VUE_APP_BASE_API,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        delFlag: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询图片资源列表 */
    getList() {
      this.loading = true;
      let queryParams = this.queryParams;
      if (queryParams.params.times && queryParams.params.times.length === 2) {
        queryParams.params.startTime = queryParams.params.times[0];
        queryParams.params.endTime = queryParams.params.times[1];
      }
      listImages(queryParams).then(response => {
        this.imagesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        imageId: null,
        gNumber: null,
        gName: null,
        imageType: null,
        imageName: null,
        imageServer: null,
        imagePath: null,
        imageHttpPath: null,
        imageHttpPath2: [],
        orderNum: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.params = {
        times: [],
        startTime: null,
        endTime: null,
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.imageId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.imageHttpPath2.push('');
      console.log('form: ', this.form);
      this.open = true;
      this.title = "添加图片资源";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const imageId = row.imageId || this.ids

      getImages(imageId).then(response => {
        let res = response.data;
        const dicts = this.dict.type.sys_goods_res_path;
        if (res.imagePath) {
          if (res.imagePath.startsWith('http')) {
            res.imageHttpPath = res.imagePath;
            res.imageHttpPath2 = [];
            res.imageHttpPath2.push(res.imagePath);
          } else {
            res.imageHttpPath2.push('http');
            if (res.imageServer === 'local') {
              res.imagePath = this.imgServe + res.imagePath;
            } else {
              for (let i = 0, len = dicts.length; i < len; i++) {
                if (dicts[i].raw.dictValue === res.imageServer) {
                  res.imagePath = dicts[i].raw.dictAttr + res.imagePath;
                }
              }
            }
          }
        }
        this.form = res;
        this.open = true;
        this.title = "修改图片信息";
      });
    },
    /** 图片提交提交表单 */
    handleImageSuccess(fileList) {
      this.submitImageForm();
    },
    /** 提交信息 */
    submitImageForm() {
      console.log('fubmit form.', this.form)
      if (this.form.imageId != null) {
        updateImages(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addImages(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.imageServer === 'http') {
            this.form.imagePath = this.form.imageHttpPath2.join(',');
          }
          if (this.form.imageServer === 'http' || this.form.imagePath) {
            this.submitImageForm();
          } else {
            let files = this.$refs.uploadImage.$refs.imageUpload.uploadFiles; // 获取选中的文件列表
            if (files && files.length > 0) {
              this.$refs.uploadImage.$refs.imageUpload.submit(); // 手动调用上传
            } else {
              this.$modal.msgError("请先选择图片");
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const imageIds = row.imageId || this.ids;
      this.$modal.confirm('是否确认删除图片资源编号为"' + imageIds + '"的数据项？').then(function () {
        return delImages(imageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/images/export', {
        ...this.queryParams
      }, `images_${new Date().getTime()}.xlsx`)
    },
    /** 上传图片数量 */
    uploadLimit(form) {
      if (form.imageId) {
        return 1;
      } else {
        return 5;
      }
    },
    /** http 图片路径修改 */
    // handleChangeHttpImage() {
      // if (this.form.imageServer === 'http' && this.form.imageHttpPath) {
      //   this.form.imageHttpPath2 = this.form.imageHttpPath.split(',');
      // } else {
      //   this.form.imageHttpPath2 = [];
      // }
    //   console.log('imageHttpPath2', this.form.imageHttpPath2);
    // },
    /** 不可修改设置 */
    isDisabled(form) {
      return !!form.imageId;
    },
    /**  */
    handleGNumberChange() {
      if (this.form && this.form.gNumber) {
        getMainByGNumber(this.form.gNumber).then(res => {
          if (res.data && res.data.goodsName) {
            this.form.gName = res.data.goodsName;
          }
        })
      }
    },
    /** */
    addHttpImage() {
      this.form.imageHttpPath2.push('');
    },
    delHttpImage(index) {
      this.form.imageHttpPath2.splice(index, 1);
    },
    getPreviewSrcList(httpPath) {
      if (httpPath) {
        let list = [];
        list.push(httpPath);
        return list;
      }
      return [];
    }
  }
};
</script>

<style scoped>
::v-deep .el-table .el-table__body-wrapper .el-table__cell {
  padding: 5px 0 2px 0;
}
.http-image-list {
  height: 100px;
  margin-right: 18px;
}
</style>
